package com.laomuji.android.mvvm.utils.permission

import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.laomuji.android.mvvm.utils.PackageUtil

/**
 * 权限申请工具,所有权限相关的操作都放在这里
 * @author laomuji666
 * @since 2024/2/20
 */
object PermissionUtil {
    private var permissionRequest: PermissionRequest? = null

    /**
     * 检查权限是否授权
     * 安卓6.0以下直接返回已授权
     * @param permission 需要检查的权限
     * @return 是否已经授权
     */
    fun isGrantedPermission(permission: String): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true
        }
        return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
            PackageUtil.getTopActivity(),
            permission
        )
    }

    /**
     * 申请权限
     * 安卓6.0以下直接触发[PermissionCallback.onGranted]
     * 安卓6.0以上会通过[PermissionRequest]申请
     */
    fun requestPermissions(
        permissionCallback: PermissionCallback?,
        vararg permissions: String,
    ) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            permissionCallback?.onGranted()
            return
        }
        permissionRequest = PermissionRequest(permissionCallback, *permissions)
        permissionRequest!!.requestPermission()
    }

    /**
     * 权限申请回调
     * 每个需要回调的Activity都需要调用该方法
     */
    fun onRequestPermissionsResult() = permissionRequest?.onRequestPermissionsResult()
}